<template>
  <div class="product">
    <div style="display:flex; justify-content:space-between;">
      <div class="topTitle" />
      <div class="topTitle title2">
        <dv-decoration-11 class="fontL" style="color: #fff;height: 100%;">{{ listQuery.lineName }}{{ $t('common.dashBoard') }}</dv-decoration-11>
      </div>
      <div class="topTitle" />
    </div>
    <div class="boardBox">
      <div class="leftBox">
        <div class="pieBox">
          <div class="pieFont">{{ $t('equipment.OPE') }}</div>
          <pie-chart :chart-data="pieChartData" :width="width" :height="height" />
        </div>
        <div class="pieBox">
          <div class="pieFont">{{ $t('equipment.LBR') }}</div>
          <pie-chart :chart-data="pieChartData2" :width="width" :height="height" />
        </div>
      </div>
      <div style="width:35%;height:100%;" class="outset">
        <img src="../../../assets/DashboardBg/bg.3.png" alt="" style="width: 100%;height: 100%;">
      </div>
      <div class="myTable" style="width: 30%;">
        <dv-scroll-board ref="scrollBoard" :config="config" style="width: 100%;height: 100%;" />
      </div>
    </div>
    <div class="container">
      <div class="detail">
        <el-row :gutter="10">
          <!-- 产出比 -->
          <el-col :xs="8" :sm="6" :md="4" :lg="3">
            <div class="detailBox">
              <div style="height:2.5vh">
                <p class="title">{{ $t('produce.produceInput') }} / {{ $t('produce.produceOutput') }} </p>
                <p class="title">{{ $t('produce.perDay') }}</p>
              </div>
              <p class="content">{{ prodectList.ProduceInput }} / {{ prodectList.ProduceOutput }}</p>
              <p class="content fontS">pcs</p>
            </div>
          </el-col>
          <!-- 生产节拍 -->
          <el-col :xs="8" :sm="6" :md="4" :lg="3"><div class="detailBox">
            <div style="height:2.5vh">
              <p class="title">{{ $t('produce.produceSpeed') }}</p>
            </div>
            <p class="content">{{ prodectList.percentA }}</p>
            <p class="content fontS">pcs / h</p>
          </div></el-col>
          <!-- 站点信息 -->
          <el-col v-for="(item, ProcessName) in statusList" :key="ProcessName" :xs="8" :sm="6" :md="4" :lg="3"><div class="detailBox">
            <div style="height:2.5vh">
              <p class="title">{{ item.StationName }}</p>
            </div>
            <p class="content" :class="item.State===$t('common.running')?fontColorG:item.State===$t('common.waitings')?fontColorY:item.State===$t('common.warning')?fontColorR:''">{{ item.State }}</p>
          </div></el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import PieChart from '@/components/Charts/PieChart.vue'
import { getLineList } from '@/api/equipment'
import screenfull from 'screenfull'
import i18n from '@/lang'
import { getBasicInfo } from '@/api/basic'
import { parseTime } from '@/utils'

export default {
  name: 'ProductView',
  components: {
    PieChart
  },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 20,
        state: 3000,
        equipDiff: 2,
        varName: 'ServerPort',
        lineNumber: '',
        lineName: '',
        stationNumber: '',
        alarmType: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      list: [],
      statusList: [],
      tableData: [],
      pieChartData: {
        point: '66',
        color: 'green'
      },
      pieChartData2: {
        point: '88',
        color: 'red'
      },
      width: '14vw',
      height: '25vh',
      prodectList: {
      },
      webClose: false,
      config: {
        header: [i18n.t('equipment.processName'), i18n.t('common.Process'), i18n.t('common.ResultStatus'), i18n.t('common.ResultValue'), i18n.t('equipment.resultUnit')],
        data: [],
        headerBGC: '#1F4A78',
        oddRowBGC: '#203757',
        evenRowBGC: '#334867',
        align: 'center',
        hoverPause: false,
        rowNum: 5
      },
      total: 0,
      fontColorR: 'red',
      fontColorY: 'yellow',
      fontColorG: 'green'
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.lineNumber !== undefined) {
          this.listQuery.lineNumber = this.$route.query.lineNumber
        }
      }
    }
  },
  created() {
    this.listQuery.lineNumber = this.$store.getters.lineNumber
  },
  mounted() {
    if (this.isEmptyLineId() === false) {
      this.getServerUrl()
    }
    this.getLineOptions()
    screenfull.toggle()
  },
  destroyed() {
    this.close()
  },
  methods: {
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取线名
    getLineOptions() {
      getLineList(this.listQuery).then(response => {
        response.data.lines.forEach(i => {
          if (i.lineNumber === this.listQuery.lineNumber) {
            this.listQuery.lineName = i.lineName
          }
        })
      })
    },
    // 获取清单
    getServerUrl() {
      getBasicInfo(this.listQuery).then(response => {
        this.list = response.data.basicInfos
        this.total = response.data.total
        if (this.total > 0) {
          this.listQuery.varName = this.list[0].varValue
          this.initWebSocket('webSocket')
        } else {
          this.$notify({
            title: this.$i18n.t('common.error'),
            message: i18n.t('msg.GET_SERVER_ADDR_ERR'),
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    getList(data) {
      console.log(data)
      this.list = data
      this.statusList = data.stations
      this.pieChartData.point = this.statusList[this.statusList.length - 1].OPE
      this.pieChartData2.point = this.statusList[this.statusList.length - 1].LBR
      this.prodectList = data.produceSummary
      this.noticeData = data.resulted
      if (this.prodectList.ProduceOutput === 0) {
        this.prodectList.percentA = 0
      } else {
        this.prodectList.percentA = this.prodectList.ProduceInput / this.prodectList.ProduceOutput
      }
      this.statusList.forEach(i => {
        if (i.State === 0) {
          i.State = i18n.t('common.unknown')
        } else if (i.State === 3) {
          i.State = i18n.t('common.waiting')
        } else if (i.State === 5) {
          i.State = i18n.t('common.warning')
        } else {
          i.State = i18n.t('common.running')
        }
      })
      this.tableData = []
      data.resulted.forEach(item => {
        let tableDatas = [item.Part.ProcessName, item.ResultName, item.ResultStatus, item.ResultValue, item.Unit]
        if (item.ResultStatus === 'OK') {
          tableDatas = [item.Part.ProcessName, item.ResultName, `<span style="color:green;">${item.ResultStatus}</span>`, item.ResultValue, item.Unit]
        } else {
          tableDatas = [item.Part.ProcessName, item.ResultName, `<span style="color:red;">${item.ResultStatus}</span>`, item.ResultValue, item.Unit]
        }
        this.tableData.push(tableDatas)
      })
      // if (this.tableData.length === 3 * this.noticeData.length) {
      //   this.tableData.splice(0, this.noticeData.length)
      // }
      // 阻止从头轮播
      this.$refs['scrollBoard'].updateRows(this.tableData)
    },
    // handleSetLineChartData(type) { },
    initWebSocket(e) {
      if (typeof WebSocket === 'undefined') {
        console.log(i18n.t('msg.WEBSOCKET_NOT_SUPPORT'))
        return
      }
      const protocol = 'ws'
      // var wsUri = protocol + '://' + '192.168.1.200' + ':' + this.listQuery.varName + process.env.VUE_APP_BASE_API + '/background/' + e
      // console.log(wsUri)
      var wsUri = protocol + '://' + window.location.hostname + ':' + this.listQuery.varName + process.env.VUE_APP_BASE_API + '/background/' + e
      this.socket = new WebSocket(wsUri)
      this.socket.onerror = this.webSocketOnError
      this.socket.onmessage = this.webSocketOnMessage
      this.socket.onclose = this.webSocketOnClose
      this.socket.onopen = this.webSocketOnOpen
    },
    webSocketOnError(e) {
      this.$notify({
        title: '',
        message: 'WebSocket连接发生错误' + e,
        type: 'error',
        duration: 3000
      })
      if (this.webClose === false) {
        setTimeout(() => {
          console.log('开始重连...')
          this.initWebSocket('webSocket')
        }, 10000)
      }
    },
    webSocketOnMessage(e) {
      this.webSocketSend(this.listQuery)
      const data = JSON.parse(e.data)
      this.getList(data)
      if (data.msgType === 'INFO') {
        this.$notify({
          title: '',
          message: data.msg,
          type: 'success',
          duration: 3000
        })
      } else if (data.msgType === 'ERROR') {
        this.$notify({
          title: '',
          message: data.msg,
          type: 'error',
          duration: 1000
        })
      }
      return data
    },
    webSocketOnClose() {
      console.log('连接已关闭...')
      if (this.webClose === false) {
        setTimeout(() => {
          console.log('开始重连...')
          this.initWebSocket('webSocket')
        }, 10000)
      }
    },
    webSocketOnOpen() {
      console.log('开启')
      this.webSocketSend(this.listQuery)
    },
    close() {
      this.webClose = true
      this.socket.close() // 关闭
    },
    webSocketSend(agentData) {
      var msg = JSON.stringify(agentData)
      if (this.socket !== undefined && this.socket.readyState === 1) {
        this.socket.send(msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.leftBox{
  display: flex;
  justify-content: space-evenly;
  height:100%;
  width: 30%;
}
.topTitle{
  width:26vw;
  height:9vh;
  margin-bottom: 1.5%
}
.title2{
  width:40vw;
}
.height{
  width:20vw;
  height:8vh;
  border-radius: 2px;
  overflow: hidden;
}
.container{
  padding: 1vh;
  background-color: #334867;
  color: #fff;
}
.product{
  padding: 2.8vh;
  min-height: 100vh;
  background-color: #203757;
}
.detailBox{
  border: 1px solid;
  height: 15vh;
  margin-top: 1vh;
}
.title{
  line-height: 1vh;
  text-align: center;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.boardBox{
  display:flex;
  height: 35vh;
  width:calc(100vw - 5.6vh);
  justify-content: space-between;
  margin-bottom: 3vh;
}
.content{
  text-align: center;
  font-weight: 600;
}
.red{
  color: rgb(193, 35, 35);
}
.yellow{
  color: rgb(208, 208, 15);
}
.green{
  color: rgb(21, 200, 21);
}
.myTable{
  height: 100%;
}
.pieBox{
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
}
.pieFont{
 color:#fff;
}
.fontL{
  font-size: 1.5rem;
}
.fontS{
  font-size: 0.9rem;
}
</style>
